package com.ruoyi.web.controller.module.event;

import java.util.List;
import java.util.Arrays;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.estate.EstateBuild;
import com.ruoyi.system.domain.module.estate.EstateBuildFloor;
import com.ruoyi.system.domain.module.event.EventPlanTask;
import com.ruoyi.system.domain.module.event.EventPlanWork;
import com.ruoyi.system.domain.module.event.EventTerminalGroup;
import com.ruoyi.system.domain.module.event.EventTerminals;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.event.*;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.web.controller.common.BaseController;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 设备组Controller
 *
 * @author ruoyi
 * @date 2023-12-25
 */
@Validated
@Api(value = "设备组控制器", tags = {"设备组管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/event/terminal/group")
public class EventTerminalGroupController extends BaseController {

    private final IEventTerminalGroupService eventTerminalGroupService;
	private final IEstateService estateService;
	private final IPropertyService propertyService;
	private final IEventTerminalsService eventTerminalsService;
	private final IEventPlanTaskService eventPlanTaskService;
	private final IEventPlanWorkService eventPlanWorkService;

    /**
     * 查询设备组列表
     */
    @ApiOperation("查询设备组列表")
    @PreAuthorize("@ss.hasPermi('module:terminalGroup:list')")
    @GetMapping("/list")
    public AjaxResult list(@Validated EventTerminalGroup eventTerminalGroup) {

		SysUser sysUser = getUser();
        QueryWrapper<EventTerminalGroup> qw = new QueryWrapper<>();

		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
			if (sysUser.getEstateId()!=null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if (eventTerminalGroup.getPropertyId()!=null){
				qw.eq("property_id",eventTerminalGroup.getPropertyId());
			}
			if (eventTerminalGroup.getEstateId()!=null){
				qw.eq("estate_id",eventTerminalGroup.getEstateId());
			}
		}
		if (eventTerminalGroup.getGroupName()!=null){
			qw.eq("group_name",eventTerminalGroup.getGroupName());
		}
		if (eventTerminalGroup.getParentId()!=null){
			qw.eq("parent_id",eventTerminalGroup.getParentId());
		}
        List<EventTerminalGroup> list = eventTerminalGroupService.list(qw);
		for (EventTerminalGroup list1:list){
			if (list1.getEstateId()!=null){
				list1.setEstateName(estateService.findById(list1.getEstateId()).getEstateName());
			}
			if (list1.getPropertyId()!=null){
				list1.setPropertyName(propertyService.findById(list1.getPropertyId()).getPropertyName());
			}
		}
        return AjaxResult.success(list);
    }

    /**
     * 导出设备组列表
     */
    @ApiOperation("导出设备组列表")
    @PreAuthorize("@ss.hasPermi('module:terminalGroup:export')")
    @Log(title = "设备组", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<EventTerminalGroup> export(@Validated EventTerminalGroup eventTerminalGroup) {
        List<EventTerminalGroup> list = eventTerminalGroupService.list();
        ExcelUtil<EventTerminalGroup> util = new ExcelUtil<EventTerminalGroup>(EventTerminalGroup.class);
        return util.exportExcel(list, "设备组");
    }

    /**
     * 获取设备组详细信息
     */
    @ApiOperation("获取设备组详细信息")
    @PreAuthorize("@ss.hasPermi('module:terminalGroup:query')")
    @GetMapping("/{id}")
    public AjaxResult<EventTerminalGroup> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Integer id) {
        EventTerminalGroup eventTerminalGroup = eventTerminalGroupService.getById(id);
        return AjaxResult.success(eventTerminalGroup);
    }

    /**
     * 新增设备组
     */
    @ApiOperation("新增设备组")
    @PreAuthorize("@ss.hasPermi('module:terminalGroup:add')")
    @Log(title = "设备组", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EventTerminalGroup eventTerminalGroup) {
		if(eventTerminalGroup.getParentId()!=null){
			if(eventTerminalGroup.getParentId() > 0){
				EventTerminalGroup parent = eventTerminalGroupService.findById(eventTerminalGroup.getParentId());
				if(parent != null){
					eventTerminalGroup.setLevel(parent.getLevel() + 1);
				}
			}else{
				eventTerminalGroup.setLevel(1);
			}
		}
        return toAjax(eventTerminalGroupService.save(eventTerminalGroup) ? 1 : 0);
    }

    /**
     * 修改设备组
     */
    @ApiOperation("修改设备组")
    @PreAuthorize("@ss.hasPermi('module:terminalGroup:edit')")
    @Log(title = "设备组", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EventTerminalGroup eventTerminalGroup) {
        return toAjax(eventTerminalGroupService.updateById(eventTerminalGroup) ? 1 : 0);
    }

    /**
     * 删除设备组
     */
    @ApiOperation("删除设备组")
    @PreAuthorize("@ss.hasPermi('module:terminalGroup:remove')")
    @Log(title = "设备组" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
		for (Integer id : ids){

			//提示有子集 无法删除
			QueryWrapper<EventTerminalGroup> qw1 = new QueryWrapper<>();
			qw1.eq("parent_id",id);
			List<EventTerminalGroup> groups = eventTerminalGroupService.list(qw1);
			if (groups.size()>0){
				return AjaxResult.error();
			}
			//提示有设备 无法删除
			QueryWrapper<EventTerminals> qw = new QueryWrapper<>();
			qw.eq("group_id",id);
			List<EventTerminals> list = eventTerminalsService.list(qw);
			if (list.size()>0){
				return AjaxResult.error();
			}
			//删除与自身有关联的 任务
			QueryWrapper<EventPlanTask> qw2 = new QueryWrapper<>();
			qw2.eq("event_target_id",id);
			List<EventPlanTask> list2 = eventPlanTaskService.list(qw2);
			for (EventPlanTask planTask : list2){
				eventPlanTaskService.removeById(planTask.getId());
			}
//			//删除与自身有关的 work
//			QueryWrapper<EventPlanWork> qw3 = new QueryWrapper<>();
//			qw3.eq("event_target_id",id);
//			List<EventPlanWork> list3 = eventPlanWorkService.list(qw3);
//			for (EventPlanWork planTask : list3){
//				eventPlanWorkService.removeById(planTask.getId());
//			}
		}
		Boolean br = eventTerminalGroupService.removeByIds(Arrays.asList(ids));
		if (br){
			return AjaxResult.success();
		}else {
			return AjaxResult.error();
		}
    }
}
